package cron

import (
	"cron-go/internal/app/cron/handlers"
	"encoding/json"
	"io/ioutil"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/go-liam/util/conv"
)

func RegisterTaskAPI(ginRouter *gin.Engine) {
	g := ginRouter.Group("/api/v1")
	g.GET("/task", GetTask)
	g.POST("/task", AddTask)
	g.PUT("/task", EditTask)
	g.PATCH("/task", UpdateTaskStatus)
	g.DELETE("task", DeleteTask)
	g.GET("/task-ready", GetReadyList)
	g.GET("/task-finish", GetFinishList)
	//g.POST("/task-run", RunTask)
	//crontab
	g.POST("/crontab-refresh", RefreshAllCronTab)
	g.POST("/crontab", BindCronTab)
	//g.DELETE("/crontab", RemoveCronTab)
}

func GetTask(c *gin.Context) {
	sv := new(handlers.GetTask)
	sv.ID = conv.StringToInt64(c.Query("id"), 0)
	println("sv.ID:", sv.ID)
	c.JSON(http.StatusOK, sv.GetData())
}

func AddTask(c *gin.Context) {
	body, _ := ioutil.ReadAll(c.Request.Body)
	sv := new(handlers.CreateTask)
	json.Unmarshal(body, &sv.Req)
	c.JSON(http.StatusOK, sv.GetData())
}

func EditTask(c *gin.Context) {
	body, _ := ioutil.ReadAll(c.Request.Body)
	sv := new(handlers.EditTask)
	json.Unmarshal(body, &sv.Req)
	c.JSON(http.StatusOK, sv.GetData())
}

func DeleteTask(c *gin.Context) {
	body, _ := ioutil.ReadAll(c.Request.Body)
	sv := new(handlers.DeleteTask)
	json.Unmarshal(body, &sv.Req)
	c.JSON(http.StatusOK, sv.GetData())
}

// func RunTask(c *gin.Context) {
// 	body, _ := ioutil.ReadAll(c.Request.Body)
// 	sv := new(handlers.RunTask)
// 	json.Unmarshal(body, &sv.Req)
// 	c.JSON(http.StatusOK, sv.GetData())
// }

func UpdateTaskStatus(c *gin.Context) {
	body, _ := ioutil.ReadAll(c.Request.Body)
	sv := new(handlers.UpdateTaskStatus)
	json.Unmarshal(body, &sv.Req)
	c.JSON(http.StatusOK, sv.GetData())
}

func GetReadyList(c *gin.Context) {
	sv := new(handlers.GetReadyTask)
	c.JSON(http.StatusOK, sv.GetData())
}

func GetFinishList(c *gin.Context) {
	sv := new(handlers.GetFinishTask)
	c.JSON(http.StatusOK, sv.GetData())
}

func RefreshAllCronTab(c *gin.Context) {
	sv := new(handlers.RefreshCrontab)
	c.JSON(http.StatusOK, sv.GetData())
}

func BindCronTab(c *gin.Context) {
	sv := new(handlers.BindCrontab)
	body, _ := ioutil.ReadAll(c.Request.Body)
	json.Unmarshal(body, &sv.Req)
	c.JSON(http.StatusOK, sv.GetData())
}
